package org.dcm4che3.tool.printscp;

import java.io.IOException;

import org.dcm4che3.data.Attributes;
import org.dcm4che3.data.Tag;
import org.dcm4che3.data.VR;
import org.dcm4che3.net.Association;
import org.dcm4che3.net.Commands;
import org.dcm4che3.net.Dimse;
import org.dcm4che3.net.Status;
import org.dcm4che3.net.pdu.PresentationContext;
import org.dcm4che3.net.service.AbstractDicomService;
import org.dcm4che3.net.service.DicomServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FilmReadyService extends AbstractDicomService {

	private final static Logger log = LoggerFactory.getLogger(FilmReadyService.class);
	
	public FilmReadyService(String ... sopClass) {
		super(sopClass);
	}
	
	@Override
	protected void onDimseRQ(Association as, PresentationContext pc, Dimse dimse, Attributes cmd, Attributes data)
			throws IOException {
		switch (dimse) {
        case N_GET_RQ:
            onNGetRQ(as, pc, cmd, data);
            break;
        default:
            throw new DicomServiceException(Status.UnrecognizedOperation);
        }
	}
	
	 protected void onNGetRQ(Association as, PresentationContext pc,
	            Attributes rq, Attributes rqAttrs) throws IOException {
        Attributes rsp = Commands.mkNGetRSP(rq, Status.Success);
//        log.info("origin======{}", rsp);
//        if (rsp.contains(Tag.CommandDataSetType)) {
//        	rsp.remove(Tag.CommandDataSetType);
//        	rsp.setInt(Tag.CommandDataSetType, VR.US, 65278);
//        }
//        log.info("rspt======{}", rsp);
        Attributes rspAttrs = create(as, rq, rqAttrs, rsp);
        Commands.setWithDatasetType(65278);
        as.tryWriteDimseRSP(pc, rsp, rspAttrs);
        Commands.setWithDatasetType(0);
    }

    protected Attributes create(Association as, Attributes rq,
            Attributes rqAttrs, Attributes rsp) throws DicomServiceException {
    	if (rqAttrs == null) {
    		rqAttrs = new Attributes();
    	}
    	
    	rqAttrs.setInt(Integer.parseInt("00080000", 16), VR.UL, 16);
    	rqAttrs.setString(Tag.Manufacturer, VR.LO, "");
    	rqAttrs.setString(Tag.ManufacturerModelName, VR.LO, "");
    	
    	rqAttrs.setInt(Integer.parseInt("00180000", 16), VR.UL, 32);
    	
    	rqAttrs.setString(Tag.DeviceSerialNumber, VR.LO, "");
    	rqAttrs.setString(Tag.SoftwareVersions, VR.LO, "");
    	rqAttrs.setString(Tag.DateOfLastCalibration, VR.DA, "");
    	rqAttrs.setString(Tag.TimeOfLastCalibration, VR.TM, "");

    	rqAttrs.setInt(Integer.parseInt("21100000", 16), VR.UL, 36);
      	rqAttrs.setString(Tag.PrinterStatus, VR.CS, "NORMAL");
    	rqAttrs.setString(Tag.PrinterStatusInfo, VR.CS, "NORMAL");
    	rqAttrs.setString(Tag.PrinterName, VR.LO, "");
    	
    	return rqAttrs;
    }
	
}
